package com.ericsson.enap.modules.monitor.service;

import com.ericsson.common.quartz.service.QuartzTableService;
import com.ericsson.common.util.ParseUrlUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

/**
 * @description:
 * @author: wangjingshi
 * @create: 2020-12-02 14:22
 */
@Component
public class EpcCronHandler implements HttpHandler {

    @Autowired
    QuartzTableService tableService;

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        //返回
        String rtn="success";
        httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
        if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
            httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
            httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
            httpExchange.sendResponseHeaders(204, -1);
            return;
        }
        httpExchange.sendResponseHeaders(200, 0);
        //获取请求路径
        URI requestURI = httpExchange.getRequestURI();
        ParseUrlUtil p = new ParseUrlUtil();
        p.parser(requestURI.toString());
        String id = (String) p.strUrlParas.get("id");
        String status = (String) p.strUrlParas.get("status");
        try {
            execCron(Long.valueOf(id),status);
        } catch (Exception e) {
            e.printStackTrace();
        }
        OutputStream responseBody = httpExchange.getResponseBody();
        responseBody.write(rtn.getBytes());
        responseBody.close();
    }

    private void execCron(Long id,String status) throws Exception {
        tableService.update(id,status);
    }


}
